﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Grid
{
    public Grid[] contains;
    private Vector2 gridPos;

    private int indexI;
    private int indexJ;
    public Grid[] neighbors;
    public int size;

    public Grid(int i, int j, int gridSize, Vector2 pos)
    {
        indexI = i;
        indexJ = j;
        size = gridSize;
        gridPos = pos;
    }
}

public class SquareGrid : MonoBehaviour
{
    // 网格宽度
    public int width;

    // 网格高度
    public int height;

    private readonly SortedDictionary<int, List<Grid>> girdDic = new SortedDictionary<int, List<Grid>>();

    public void initGrid()
    {
        var grid = new Grid(0, 0, Mathf.Min(width, height), new Vector2(transform.position.x, transform.position.z));
        var gridList = new List<Grid> { grid };
        girdDic[grid.size] = gridList;
    }

    public void PutItem(int itemSize)
    {
        if (girdDic.Count == 0)
            initGrid();
        else if (girdDic.Count == 1) GeneratorOneGridLayer(itemSize);

        var gridSize = 0;
        for (var i = 0; i < girdDic.Count - 1; i++)
        {
            var item = girdDic.ElementAt(i);
            var itemNext = girdDic.ElementAt(i + 1);
            Debug.Log("key is " + item.Key);
            Debug.Log("value is " + item.Value);
            if (itemSize > item.Key && itemSize < itemNext.Key)
            {
                gridSize = itemNext.Key;
                break;
            }
        }
    }

    private void GeneratorOneGridLayer(int itemSize)
    {
        var gridList = new List<Grid>();
        var row = width / itemSize;
        var col = height / itemSize;
        for (var i = 0; i < row; i++)
        for (var j = 0; j < col; j++)
        {
            var pos = new Vector2();
            var grid = new Grid(i, j, itemSize, pos);
            gridList.Add(grid);
        }
    }
}